<?php

namespace app\common\validate\site;

use app\common\service\CommonSiteConfigService;
use app\model\site\User;
use think\Validate;

class UserValidate extends Validate
{

    protected $rule =   [
        'id' => 'require',
        'site_id' => 'require',
        'username' => 'checkUsername',
        'password' => 'checkPassword',
        'register_platform' => 'require',
        'mobile' => 'require|checkMobile'
    ];

    protected $message  =   [
        'register_platform.require' => '缺少注册平台'
    ];

    public function sceneOauthAdd (): UserValidate
    {
        return $this->only(['site_id', 'nickname', 'mobile', 'register_platform'])->remove('mobile','require');
    }

    /** 添加场景验证
     * @return UserValidate
     */
    public function sceneAdd (): UserValidate
    {
        return $this->remove('id','require');
    }

    /** 编辑场景验证
     * @return UserValidate
     */
    public function sceneEdit (): UserValidate
    {
        return $this;
    }

    protected function checkUsername($value, $rule, $data): bool|string
    {
//        第一个字符为英文，只能用字母、数字、汉字、下划线，总长度限制在4-12位的用户名
        if (!$value){
            return true;
        }else if (!validateUsername($value)){
            return '用户名第一个字符必须为英文，只能由4-12位的字母、数字、汉字、下划线组成';
        }else {
            $id = User::where('site_id', $data['site_id'])->where('username', $value)->value("id");
            if ($id){
                return "用户名重复";
            }
        }
        return true;
    }

    protected function checkPassword($value, $rule, $data=[]): bool|string
    {
        if(!$value){
            return true;
        }elseif (!validatePassword($value)){
            return '密码必须包含字母、数字和符号中的两种，由8-16位组成';
        }
        return true;
    }

    protected function checkMobile($value, $rule, $data=[]): bool|string
    {
        // 验证手机号，如果开启了强制绑定手机号，则手机号必填，且不能重复
        $login = CommonSiteConfigService::instance()->getConfigValue($data['site_id'], CommonSiteConfigService::LOGIN);
        if ($login['is_force_bind_mobile'] == 1 && !$value){
            return "必须填写手机号码";
        }
        if ($value && !validateMobile($value)){
            return "手机号码格式错误";
        }
        if ($value){
            $id = User::where('site_id', $data['site_id'])->where('mobile', $value)->value('id',0);
            if ($id != ($data['id']??0)){
                return "手机号码已被占用，请更换其他手机号";
            }
        }

        return true;
    }

}
